/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package breakupndefmessage;

import com.ericsson.nfc.signing.record.CertificateField;
import com.ericsson.nfc.signing.record.InvalidSignatureRecord;
import com.ericsson.nfc.signing.record.SignatureField;
import com.ericsson.nfc.signing.record.SignatureRecord;
import com.ericsson.nfc.signing.record.URIRecord;
import java.io.IOException;
import javax.microedition.midlet.*;

//#ifdef MyJSR257
//# import my.javax.microedition.contactless.ndef.NDEFMessage;
//# import my.javax.microedition.contactless.ndef.NDEFRecord;
//#else
import javax.microedition.contactless.ndef.NDEFMessage;
import javax.microedition.contactless.ndef.NDEFRecord;
//#endif

import parser.NDEFParser;

/**
 * @author emarkki
 */
public class Midlet extends MIDlet {
    
    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
    
    void parse(String title, String file) {
        try {
            System.out.println("--- " + title + " ---");
            NDEFMessage msg = new NDEFMessage(Data.readBinaryFile(file), 0);
            dump(msg);
            System.out.println();
            //System.out.println("Offset\tContent\tExplaination");
            byte[] msgSpUrlAUser1Bytes = msg.toByteArray();
            NDEFParser parser = new NDEFParser();
            System.out.println(parser.parse(msgSpUrlAUser1Bytes));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        System.out.println();
        System.out.println();
    }

    public void startApp() {
        System.out.println("BreakUpNDEFMessage");
        System.out.println();
        

        parse("msgSpUrlMinUser1SigRSASSAPSS", Data.msgSpUrlMinUser1SigRSASSAPSS);
        parse("msgSpUrlMinUser1SigRSAPKCS1", Data.msgSpUrlMinUser1SigRSAPKCS1);
        parse("msgSpUrlMinUser2SigDSA", Data.msgSpUrlMinUser2SigDSA);
        parse("msgSpUrlMinUser3SigECDSA", Data.msgSpUrlMinUser3SigECDSA);

        parse("msgSpUrlAUser1", Data.msgSpUrlAUser1);
        parse("msgSpUrlAUser2", Data.msgSpUrlAUser2);
        parse("msgSpUrlAUser3", Data.msgSpUrlAUser3);
        parse("msgSpUrlAUser4", Data.msgSpUrlAUser4);
        parse("msgSpUrlBUser1", Data.msgSpUrlBUser1);
        parse("msgSpUrlBUser2", Data.msgSpUrlBUser2);
        parse("msgSpUrlCUser1", Data.msgSpUrlCUser1);
        parse("msgSpUrlDUser1", Data.msgSpUrlDUser1);
        parse("msgSpUrlDUser2", Data.msgSpUrlDUser2);
        parse("msgSpUrlDUser3", Data.msgSpUrlDUser3);
        parse("msgSpUrlDUser4", Data.msgSpUrlDUser4);

        
        System.out.println("done");
    }
    
    private void dump(NDEFMessage msg) {
        StringBuffer sb = new StringBuffer();
        dump(msg, "", sb);
        System.out.println(sb.toString());
    }
    
    private void dump(NDEFMessage msg, String prefix, StringBuffer sb) {
        sb.append(prefix + "Message[" + msg.toByteArray().length + " bytes, " + msg.getNumberOfRecords() + " records] {" + "\n");
        
        for(int i = 0; i < msg.getNumberOfRecords(); i++) {            
            dumpRecord(msg.getRecord(i), prefix+"\t", sb);
        }
        sb.append(prefix + "}\n");
    }
    
    private void dumpRecord(NDEFRecord r, String prefix, StringBuffer sb) {
            
        sb.append(prefix + "Record(" + r.getRecordType().getName() + ", id="+Utils.toBinaryString(r.getId())+", payload="+r.getPayloadLength()+" bytes) {\n");

        if("Sp".equals(r.getRecordType().getName())) {
            dumpSp(r, prefix+"\t", sb);
        } else if("U".equals(r.getRecordType().getName())) {
            dumpU(r, prefix+"\t", sb);
        } else if("Sig".equals(r.getRecordType().getName())) {
            dumpSig(r, prefix+"\t", sb);
        }

        sb.append(prefix + "}\n");
    }
    
    private void dumpSp(NDEFRecord r, String prefix, StringBuffer sb) {
        if(!"Sp".equals(r.getRecordType().getName())) {
            throw new RuntimeException("Not a Sp");
        }
        
        NDEFMessage sp = r.getNestedNDEFMessage(0);
        dump(sp, prefix, sb);
    }
    
    private void dumpU(NDEFRecord r, String prefix, StringBuffer sb) {
        if(!"U".equals(r.getRecordType().getName())) {
            throw new RuntimeException("Not an U");
        }
        
        URIRecord uri = new URIRecord(r.getPayload(), 0);
        
        sb.append(prefix + uri.getURI() + "\n");
    }
    
    private void dumpSig(NDEFRecord r, String prefix, StringBuffer sb) {
        if (!"Sig".equals(r.getRecordType().getName())) {
            throw new RuntimeException("Not an Sig");
        }
        
        try {
            SignatureRecord sig = new SignatureRecord(r.getPayload(), 0);

            sb.append(prefix + "Version: " + sig.getVersion() + "\n");
            sb.append(prefix + "Marker: " + sig.isMarker() + "\n");
            dumpSigField(sig.getSignatureField(), prefix, sb);
            dumpCertField(sig.getCertificateField(), prefix, sb);
            
        } catch (InvalidSignatureRecord ex) {
            System.out.println(prefix + "InvalidSignatureRecord: " + ex.getMessage());
        }
    }
    
    private void dumpCertField(CertificateField field, String prefix, StringBuffer sb) {
        if(field == null) {
            return;
        }
        
        sb.append(prefix + "Certificate Field {\n");
        
        sb.append(prefix+"\t" + "Format: " + field.getFormat() + "\n");
        sb.append(prefix+"\t" + "URI: " + field.getUri() + "\n");
        String s = "";
        for(int i = 0; i < field.getChain().length; i++) {
            s+= field.getChain()[i].getBytes().length;
            if(i!= field.getChain().length-1) {
                s+= ",";
            }
        }
        sb.append(prefix+"\t" + "Chain: " + s + " bytes\n");
        sb.append(prefix + "}\n");
    }
    
    private void dumpSigField(SignatureField field, String prefix, StringBuffer sb) {
        if(field == null) {
            return;
        }
        
        sb.append(prefix + "Signature Field {\n");
        
        sb.append(prefix+"\t" + "Type: " + field.getType() + "\n");
        
        if(field.getUri() != null) {
            sb.append(prefix+"\t" + "URI: " + field.getUri() + "\n");
        }
        if(field.getSignature() != null) {
            sb.append(prefix+"\t" + "Signature: " + field.getSignature().length + " bytes\n");
        }

        sb.append(prefix + "}\n");
    }
}
